package com.tvserials.notification.preferences;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.util.Log;
import com.tvserials.notification.dto.Episode;
import com.tvserials.notification.dto.Serial;
import com.tvserials.notification.vo.SourceType;

import java.io.*;
import java.util.*;

/**
 * Created by oleksandr.dokienko on 3/26/2014.
 */
public class SharedPreferencesUtils {

    public static final String SYNC_SERVICE = "SyncServ";

    public static final String SYNC_TIME_KEY = "syncTime";
    public static final String SERIAL_LIST = "serialList";
    public static final String PREF_SYNC_FREQUENCY = "prefSyncFrequency";
    public static final String EPISODES_CACHE = "episodesCache";
    private static final String TAG = "SharedPreferencesUtils";
    public static final String NAV_POSITION_KEY = "navPosition";
    public static final String TILE_LAYOUT_KEY = "tileLayout";
    public static final String KEY_USER = "user";
    public static final String KEY_TOKEN = "token";

    public static Date getSyncDate(Context context) {
        SharedPreferences settings = context.getSharedPreferences(SYNC_SERVICE, 0);
        long syncTime = settings.getLong(SYNC_TIME_KEY, 0);
        if (syncTime != 0) {
            GregorianCalendar gregorianCalendar = new GregorianCalendar();
            gregorianCalendar.setTimeInMillis(syncTime);
            Log.w(TAG, "Get Sync Date:" + gregorianCalendar.getTime());
            return gregorianCalendar.getTime();
        }
        return null;
    }

    public static void updateSyncDate(Context context, Date syncDate) {
        long dateTimeInMill = 0;
        if (syncDate != null) {
            GregorianCalendar gregorianCalendar = new GregorianCalendar();
            gregorianCalendar.setTime(syncDate);
            dateTimeInMill = gregorianCalendar.getTimeInMillis();
        }
        SharedPreferences settings = context.getSharedPreferences(SYNC_SERVICE, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong(SYNC_TIME_KEY, dateTimeInMill);
        editor.commit();
        Log.w(TAG, "Save Sync Date:" + new Date(dateTimeInMill));
    }

    public static void clearData(Context context) {
        context.getSharedPreferences(SYNC_SERVICE, 0).edit().clear().commit();
    }

    public static void saveSerialsList(Context context, List<Serial> outputStrArr) {
        saveObject(context, outputStrArr, "serialList");
        Log.w(TAG, "Saved list of serials");
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static List<Serial> getSerialsList(Context context) {
        Object object = getObject(context, "serialList");
        if (object != null) {
            return (List<Serial>) object;
        }
        return new ArrayList<Serial>();
    }

    public static int getSyncIntervalTime(Context context) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        String prefSyncFrequency = sharedPrefs.getString(PREF_SYNC_FREQUENCY, "0");
        return Integer.valueOf(prefSyncFrequency);
    }

    public static boolean getUseOnlyWifi(Context context) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        return sharedPrefs.getBoolean("prefUseWifiOnly", false);
    }

    public static boolean getIndicator(Context context) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        return sharedPrefs.getBoolean("prefIndicator", false);
    }

    public static boolean getVibration(Context context) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        return sharedPrefs.getBoolean("prefVibration", false);
    }

    public static Uri getRingtoneUri(Context context) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        return Uri.parse(sharedPrefs.getString("prefAudio", "DEFAULT_SOUND"));
    }

    public static Date getStartTime(Context context) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        long prefStart = sharedPrefs.getLong("prefStart", new Date().getTime());
        return new Date(prefStart);
    }

    public static Date getEndTime(Context context) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        long prefEnd = sharedPrefs.getLong("prefEnd", new Date().getTime());
        return new Date(prefEnd);
    }

    public static boolean isTileLayout(Context context) {
        SharedPreferences settings = context.getSharedPreferences(SYNC_SERVICE, 0);
        return settings.getBoolean(TILE_LAYOUT_KEY, false);
    }

    public static void saveTileLayout(Context context, boolean isTileLayout) {
        SharedPreferences settings = context.getSharedPreferences(SYNC_SERVICE, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(TILE_LAYOUT_KEY, isTileLayout);
        editor.commit();
    }

    public static void saveNavigationItemPosition(Context context, int position) {
        SharedPreferences settings = context.getSharedPreferences(SYNC_SERVICE, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(NAV_POSITION_KEY, position);
        editor.commit();
    }

    public static int getNavigationItemPosition(Context context) {
        SharedPreferences settings = context.getSharedPreferences(SYNC_SERVICE, 0);
        return settings.getInt(NAV_POSITION_KEY, 0);
    }

    public static int getHistoryNo(Context context) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        String historyNo = sharedPrefs.getString("prefHistory", "15");
        return Integer.valueOf(historyNo);
    }

    public static void saveEpisodes(Context context, List<Episode> episodes) {
        saveObject(context, episodes, SharedPreferencesUtils.EPISODES_CACHE);
    }

    public static void setUser(Context context, String user) {
        SharedPreferences preferences = context
                .getSharedPreferences("auth", Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(KEY_USER, user);
        editor.commit();
    }

    public static List<SourceType> getSelectedSourceTypes(Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        Set<String> sourceItems = preferences.getStringSet("sourceItems", new HashSet<String>(
                Arrays.asList("1", "2", "3")));
        List<SourceType> selectedSourceSystems = new ArrayList<SourceType>();
        for (String item : sourceItems) {
            SourceType sourceType = SourceType.getSourceTypeByPosition(Integer.valueOf(item));
            selectedSourceSystems.add(sourceType);
        }
        return selectedSourceSystems;
    }

    /* public static void setToken(Context context, String password) {
         SharedPreferences preferences = context
                 .getSharedPreferences("auth", Context.MODE_PRIVATE);

         SharedPreferences.Editor editor = preferences.edit();
         editor.putString(KEY_TOKEN, password);
         editor.commit();
     }

     public static String getToken(Context context) {
         SharedPreferences preferences = context
                 .getSharedPreferences("auth", Context.MODE_PRIVATE);
         return preferences.getString(KEY_TOKEN, null);
     }

 */
    public static String getUser(Context context) {
        SharedPreferences preferences = context
                .getSharedPreferences("auth", Context.MODE_PRIVATE);

        return preferences.getString(KEY_USER, null);
    }

    public static List<Episode> getEpisodes(Context context) {
        Object object = getObject(context, EPISODES_CACHE);
        if (object != null) {
            return (List<Episode>) object;
        }
        return new ArrayList<Episode>();
    }

    private static void saveObject(Context context, Object object, String fileName) {
        try {
            FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(object);
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Object getObject(Context context, String fileName) {
        try {
            File fileStreamPath = context.getFileStreamPath(fileName);
            if (fileStreamPath.exists()) {
                FileInputStream fos = context.openFileInput(fileName);
                ObjectInputStream os = new ObjectInputStream(fos);
                Object readObject = os.readObject();
                os.close();
                return readObject;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
